package com.rzico.sbl.ui.report.dispatch

import android.text.InputFilter
import androidx.core.view.isVisible
import androidx.core.widget.doAfterTextChanged
import com.jeremyliao.liveeventbus.LiveEventBus
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityReportDispatchThirdBinding
import com.rzico.sbl.other.serviceStep
import com.rzico.sbl.ui.report.other.goToOrderDetail
import com.rzico.sbl.viewmodel.ReportDispatchViewModel
import com.xinnuo.common.extend.*
import com.xinnuo.common.helper.ActivityStack
import com.xinnuo.common.helper.doubleValue
import com.xinnuo.common.other.DecimalNumberFilter
import com.xinnuo.common_ui.base.BaseActivity
import com.xinnuo.common_ui.utils.bindLifeCycle
import com.xinnuo.common_ui.utils.showHintDialog
import com.xinnuo.common_ui.utils.subscribeBySuccess
import org.json.JSONObject

class ReportDispatchThirdActivity : BaseActivity(R.layout.activity_report_dispatch_third) {

    private val mBinding by lazy { ActivityReportDispatchThirdBinding.bind(getRootView()) }

    private var mShippingSn = ""

    override fun getViewModel() = get<ReportDispatchViewModel>()

    override fun initData() {
        initTitle(title = "送达")

        getData()
    }

    override fun initListener() {
        mBinding.apply {
            thirdTicket.filters = arrayOf(DecimalNumberFilter(), InputFilter.LengthFilter(8))
            thirdOld.filters = arrayOf(DecimalNumberFilter(), InputFilter.LengthFilter(8))
            thirdOut.filters = arrayOf(DecimalNumberFilter(), InputFilter.LengthFilter(8))
            thirdWechat.filters = arrayOf(DecimalNumberFilter(), InputFilter.LengthFilter(8))
            thirdAlipay.filters = arrayOf(DecimalNumberFilter(), InputFilter.LengthFilter(8))
            thirdCash.filters = arrayOf(DecimalNumberFilter(), InputFilter.LengthFilter(8))

            thirdTotal.doAfterTextChanged { totalDebt() }
            thirdTicket.doAfterTextChanged { totalDebt() }
            thirdOld.doAfterTextChanged { totalDebt() }
            thirdOut.doAfterTextChanged { totalDebt() }
            thirdReal.doAfterTextChanged { totalDebt() }

            thirdWechat.doAfterTextChanged { totalReal() }
            thirdAlipay.doAfterTextChanged { totalReal() }
            thirdCash.doAfterTextChanged { totalReal() }

            thirdPayLl.oneClick {
                if (serviceStep == "2") {
                    goToOrderDetail(
                        "title" to "运单详情",
                        "orderSn" to intent.getExtra("orderSn")
                    )
                }
            }

            btSend.oneClick {
                if (mShippingSn.isEmpty()) {
                    showToast("获取信息失败，请返回重试")
                    return@oneClick
                }

                showHintDialog(
                    title = "确认送达",
                    hint = "确定要完成送达吗？",
                    onSure = {
                        getViewModel()
                            .dispatchThird(
                                "sn" to intent.getExtra("shippingSn"),
                                "exchangePrice" to thirdTicket.textOrEmpty("0.00"),
                                "weixinPay" to thirdWechat.textOrEmpty("0.00"),
                                "aliPay" to thirdAlipay.textOrEmpty("0.00"),
                                "cashPay" to thirdCash.textOrEmpty("0.00"),
                                "repayment" to thirdBack.textOrEmpty("0.00"),
                                "payAmount" to thirdOut.textOrEmpty("0.00"),
                                "amountPaid" to thirdReal.content,
                                "arrears" to thirdNew.content,
                                "memo" to thirdMemo.content
                            )
                            .bindLifeCycle(getLifecycleOwner())
                            .subscribeBySuccess(
                                event = getViewModel(),
                                onSuccess = {
                                    showToast("确认送达成功！")

                                    // 刷新报货运单列表
                                    LiveEventBus
                                        .get("deliverModify")
                                        .post("refresh")

                                    ActivityStack.screenManager.popActivities(
                                        ReportDispatchThirdActivity::class.java,
                                        ReportDispatchSecondActivity::class.java,
                                        ReportDispatchRottenActivity::class.java,
                                        ReportDispatchFirstActivity::class.java
                                    )
                                }
                            )
                    }
                )
            }
        }
    }

    /**
     * 送达详情
     */
    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel()
            .dispatchPay(intent.getExtra("shippingSn"))
            .bindLifeCycle(getLifecycleOwner())
            .subscribeBySuccess(
                event = getViewModel(),
                onSuccess = { result ->
                    val obj = JSONObject(result)

                    // 运单编号，判断是否请求成功
                    mShippingSn = obj.optNotNull("sn")

                    mBinding.apply {
                        val amountBucket = obj.optNotNull("barrelPrice").doubleValue
                        val amountRotten = obj.optNotNull("swapPrice").doubleValue
                        val amountPay =
                            when (serviceStep) {
                                "2" -> {
                                    thirdTicketLl.visible()
                                    thirdPayArrow.visible()
                                    obj.optNotNull("amountPayable").doubleValue
                                }
                                else -> {
                                    thirdTicketLl.gone()
                                    thirdPayArrow.gone()
                                    obj.optNotNull("subPrice").doubleValue
                                }
                            }

                        thirdTotal.text = (amountBucket + amountPay - amountRotten).formatDecimal()
                        thirdBucket.text = amountBucket.formatDecimal()
                        thirdPay.text = amountPay.formatDecimal()

                        // 烂桶金额
                        amountRotten.also {
                            thirdRottenLl.isVisible = it > 0
                            thirdRotten.text = "-${amountRotten.formatDecimal()}"
                        }

                        // 运费金额
                        obj.optNotNull("freightPayable")
                            .also {
                                thirdFeeLl.isVisible = it.doubleValue > 0
                                thirdFee.text = it.formatDecimal()
                            }

                        // 水票金额
                        obj.optNotNull("exchangePrice")
                            .apply {
                                if (doubleValue > 0)
                                    thirdTicket.setText(formatDecimal())
                            }

                        // 以往欠款
                        obj.optNotNull("debt")
                            .apply {
                                if (doubleValue > 0)
                                    thirdOld.setText(formatDecimal())
                            }
                    }

                    // 收货信息
                    val objReceive = obj.optJSONObject("receiver") ?: JSONObject()
                    mBinding.apply {
                        thirdName.text = objReceive.optNotNull("consignee")
                        thirdPhone.text = objReceive.optNotNull("phone")
                        thirdAdress.text = objReceive.optNotNull("address")
                    }
                }
            )
    }

    /**
     * 累计欠款计算
     */
    private fun totalDebt() {
        mBinding
            .apply {
                val amountThis = thirdTotal.textDouble - thirdTicket.textDouble
                val amountOld = thirdOld.textDouble
                val amountOut = thirdOut.textDouble
                val amountReal = thirdReal.textDouble

                thirdNew.text = (amountThis + amountOld - amountReal + amountOut).formatDecimal()

                if (amountOld > 0 && amountReal > amountThis) {
                    val amountBack = amountReal - amountThis
                    thirdBack.text =
                        (if (amountBack < amountOld) amountBack else amountOld).formatDecimal()
                } else thirdBack.text = "0.00"
            }
    }

    /**
     * 实收金额计算
     */
    private fun totalReal() {
        mBinding
            .apply {
                val amountWechat = thirdWechat.textDouble
                val amountAlipay = thirdAlipay.textDouble
                val amountCash = thirdCash.textDouble

                thirdReal.text = (amountWechat + amountAlipay + amountCash).formatDecimal()
            }
    }

}